package com.lark.utils;

import com.google.common.base.Charsets;
import com.lark.exception.FileException;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.Arrays;
import java.util.stream.Collectors;

@Slf4j
public final class FileUtil {

    /**
     * 解析文件
     *
     * @param filePath
     * @return String
     */
    public static String parse(String filePath) {
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath, Charsets.UTF_8))) {
            // 读取整个文件内容
            return reader.lines().collect(Collectors.joining(System.lineSeparator()));
        } catch (IOException e) {
            throw new FileException("文件解析异常: " + e.getMessage());
        }
    }

    /**
     * 更新文件
     *
     * @param filePath
     * @param data
     */
    public static void save(String filePath, String data) {
        try (Writer writer = new FileWriter(filePath)) {
            writer.write(data);
            writer.flush();
        } catch (IOException e) {
            throw new FileException("文件更新异常: " + e.getMessage());
        }
    }

    /**
     * 删除文件
     *
     * @param file
     */
    public static void delete(File file) {
        if (file.exists()) {
            boolean delete = file.delete();
            if (delete) {
                log.info("JSON文件删除成功");
            } else {
                log.error("JSON文件删除失败");
            }
        }
    }

    /**
     * 批量删除文件
     *
     * @param folder
     */
    public static void batchDelete(File folder) {
        if (folder.isDirectory()) {
            File[] files = folder.listFiles();
            if (files == null || files.length == 0) {
                log.error("文件夹为空: {}", folder.getPath());
                return;
            }

            Arrays.stream(files).parallel().forEach(file -> {
                if (file.isDirectory()) {
                    batchDelete(file);
                } else {
                    delete(file);
                }
            });
        } else {
            delete(folder);
        }
    }
}
